package com.qiangesoft.mqtt.producer;

import com.qiangesoft.mqtt.config.MqttProperty;
import com.qiangesoft.mqtt.constant.MqttConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * mqtt生产者
 *
 * @author qiangesoft
 * @date 2024-04-24
 */
@Configuration
public class MqttProducerConfig {

    @Autowired
    private MqttProperty mqttProperty;
    @Autowired
    private MqttPahoClientFactory mqttPahoClientFactory;

    /**
     * 消息生产通道
     *
     * @return
     */
    @Bean(name = MqttConstant.OUTBOUND_CHANNEL)
    public MessageChannel outboundChannel() {
        return new DirectChannel();
    }

    /**
     * 消息发布
     *
     * @return
     */
    @Bean
    @ServiceActivator(inputChannel = MqttConstant.OUTBOUND_CHANNEL)
    public MessageHandler mqttOutbound() {
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(mqttProperty.getProducer().getClientId(), mqttPahoClientFactory);
        messageHandler.setAsync(false);
        messageHandler.setDefaultQos(mqttProperty.getProducer().getQos());
        messageHandler.setDefaultTopic(mqttProperty.getProducer().getTopic());
        return messageHandler;
    }
}
